//
//  LineLayout.m
//  自定义布局
//
//  Created by 耐克了解了 on 17/4/17.
//  Copyright © 2017年 耐克了解了. All rights reserved.
//

#import "LineLayout.h"

@implementation LineLayout

-(instancetype)init
{
    if (self = [super init]) {
       
        //总结：
        // 1. prepareLayout 初始化方法
        // 2.layoutAttributesForElementsInRect:(CGRect)rect
        // 3.这个方法的返回值就决定了collectionView停止滚动时的偏移位置
       
    }
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
    CGFloat insert = (self.collectionView.frame.size.width - self.itemSize.width )*0.5;
    self.sectionInset = UIEdgeInsetsMake(0, insert, 0, insert);
}

//当collectionView显示的范围发生改变的时候，是否需要更新布局
//一旦重新刷新，就会调用下面这个方法

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
    
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    //获得父类已计算好的属性
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    
    //计算collectionView最中心点的X点
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width *0.5;
    
    //在原有布局的基础上处理cell的变化
    for (UICollectionViewLayoutAttributes *attrs in array) {
//        CGFloat scale = arc4random_uniform(100)/100.0;
//        attrs.transform = CGAffineTransformMakeScale(scale, scale);
        // 每一个cell中心点 attrs.center
        
     
        CGFloat delta = ABS(attrs.center.x -centerX);
        CGFloat scale = 1.2 - (delta / self.collectionView.frame.size.width);
        
        //NSLog(@"%f",attrs.center.x -centerX );
        
        //设置transdorm
        attrs.transform = CGAffineTransformMakeScale(scale, scale);
    }
    
    return array;
}

//3.这个方法的返回值就决定了collectionView停止滚动时的偏移位置
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    CGRect  rect;
    rect.origin.y = 0;
    rect.origin.x = proposedContentOffset.x;
    rect.size = self.collectionView.frame.size;
    
    
    NSArray *array =  [super layoutAttributesForElementsInRect: rect];
    
    //计算collectionView最中心的X
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width *0.5;
    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes*attrs in array) {
        
        if (ABS(minDelta) > ABS(attrs.center.x - centerX )) {
            minDelta = attrs.center.x - centerX;
        }
    }
    
    proposedContentOffset.x += minDelta;
    return  proposedContentOffset;
}







@end
